// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','starter.config', 'pascalprecht.translate'])

.run(function($ionicPlatform, $location, DB, DB_CONFIG, APP) { //CordovaService, 
	var authorized = false;
   //var bluetoothle;
  $ionicPlatform.ready(function() {	
	//TODO: tmp
      console.log("ready");
   DB.db = window.sqlitePlugin.openDatabase({name: DB_CONFIG.name}); //in production
   
   
			angular.forEach(DB_CONFIG.tables, function(table) {
				var columns = [];
	 
				angular.forEach(table.columns, function(column) {
					columns.push(column.name + ' ' + column.type);
				});
	 
				var query = 'CREATE TABLE IF NOT EXISTS ' + table.name + ' (' + columns.join(',') + ')';
				DB.query(query);
				//console.log('Table ' + table.name + ' initialized');
			});
			
			//var query = 'INSERT INTO exercises (name, person_id) VALUES ("teste", 1)';
			//self.query(query);   
   
   
	//if(!DB.production){
		//DB.init();
		
      
      
		
		var data = JSON.parse(localStorage.getItem("person"));
		
		//console.log(JSON.stringify(data));
		if( (data !== null) && (data[0]['message'] == 'success')){
			//$scope.user_id = data[0]['user_id'];
			APP.user_id = data[0]['user_id'];
		}
		else
		{
			//$scope.user_id = 0;
			APP.user_id = 0;		
		}
		
		$location.path('/app/resume');
	//}

    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    //if(window.cordova && window.cordova.plugins.Keyboard) {
     // cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    //}
    if(window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }	 
  });
 })

.config(function($stateProvider, $urlRouterProvider, $translateProvider	) {
  $stateProvider

    .state('app', {
      url: "/app",
      abstract: true,
      templateUrl: "templates/menu.html",
      controller: 'AppCtrl'
    })

    .state('app.new_exercise', {
      url: "/new_exercise",
      views: {
        'menuContent' :{
          templateUrl: "templates/new_exercise.html",
		  controller: 'NewExerciseCtrl'
        }
      }
    })

    .state('app.configure_exercise', {
      url: "/configure_exercise",
      views: {
        'menuContent' :{
          templateUrl: "templates/pre_exercise.html"
        }
      }
    })	

    .state('app.exercises', {
      url: "/exercises",
      views: {
        'menuContent' :{
          templateUrl: "templates/exercises.html",
          controller: 'ExercisesCtrl'
        }
      }
    })

	.state('app.exercise_detail', {
		url: '/exercise/:id',
		views: {
			'menuContent' : {
				templateUrl: 'templates/exercise_detail.html',
				controller: 'ExerciseDetailCtrl'
			}
		}
	})
	
	.state('app.resume', {
		url: '/resume',
		views: {
			'menuContent' : {
				templateUrl: 'templates/resume.html',
				controller: 'ResumeCtrl'
			}
		}
	})
	
	.state('app.while_exercise', {
		url: '/while_exercise',
		views: {
			'menuContent' : {
				templateUrl: 'templates/while_exercise.html',
				controller: 'WhileExerciseCtrl'
			}
		}
	})
	
	.state('app.exercise_options', {
		url: '/exercise_options',
		views: {
			'menuContent' : {
				templateUrl: 'templates/exercise_options.html',
				controller: 'ExerciseDetailCtrl'
			}
		}
	})
	
	.state('app.configuration', {
		url: '/configuration',
		views: {
			'menuContent' : {
				templateUrl: 'templates/configuration.html',
				controller: 'ConfigurationCtrl'
			}
		}
	});
	
	$translateProvider.translations('en_US', {
		exercise: "Exercise",
		last_exercise: "Last exercise",
		last_week: "Last week",
		last_month: "Last month",
		date: "Date",
		duration: "Duration",
		time: "Time",
		distance: "Distance",
		speed: "Speed",
		score: "Score",
		calories: "Calories",
		accuracy: "Accuracy",
		type: "Type",
		workout_plan: "Workout plan",
		shoes: "Shoes",
		start: "Start",
		stop: "Stop",
		cancel: "Cancel",
		home: "Home",
		historic: "Historic",
		close: "Close",
		run: "Run",
		ride: "Ride",
		walking: "Walking",
		resume: "Resume",
		during_exercise: "During exercise",
		network_error: "Network error, not conected!",
		starting_exercise: "Starting exercise!",
		finished_exercise: "Finished exercise!",
		upload_sucess: "Uploaded successfully!",
		upload_error: "Upload error!",
		permission_denied: "Permission denied to access satellite",
		invalid_username_password: "Username or password invalid",
		deleted_exercise: "Deleted exercise!",
		options: "Options",
		edit: "Edit",
		sure_delete: "Are you sure you want to delete this exercise?",
		sure_upload: "Are you sure you want to upload this exercise?",
		sure_logout: "Are you sure you want to logout?",
		exercise_detail: "Exercise detail",
		points: "Points",
		graphics: "Graphics",
		partial: "Partial",
		back: "Back",
		configuration: "Configuration",
		portuguese: "Portuguese",
		english: "English",
      exercises_number: "Num. exercises"
	});
	$translateProvider.translations('pt_BR', {
		exercise: "Exercício",
		last_exercise: "Último exercício",
		last_week: "Última semana",
		last_month: "Último mês",
		date: "Data",
		duration: "Duração",
		time: "Tempo",
		distance: "Distância",
		speed: "Veloc.",
		score: "Pontuação",
		calories: "Calorias",
		accuracy: "Precisão",
		type: "Tipo",
		workout_plan: "Plano treino",
		shoes: "Tênis",
		start: "Iniciar",
		stop: "Parar",
		cancel: "Cancelar",
		home: "Inicio",
		historic: "Histórico",
		close: "Fechar",
		run: "Corrida",
		ride: "Bike",
		walking: "Caminhada",
		resume: "Resumo",
		during_exercise: "Durante exercício",
		network_error: "Erro de rede, não conectado!",
		starting_exercise: "Começando exercício!",
		finished_exercise: "Exercício terminado!",
		upload_sucess: "Upload com sucesso!",
		upload_error: "Upload erro!",
		permission_denied: "Permisão negada para acessar satélite!",
		invalid_username_password: "Nome de usuário ou senha inválidos!",
		deleted_exercise: "Exercício deletado!",
		options: "Opções",
		edit: "Editar",
		sure_delete: "Tem certeza que deseja deletar este exercício?",
		sure_upload: "Tem certeza que deseja fazer upload deste exercício?",
		sure_logout: "Tem certeza que deseja desvincular sua conta?",
		exercise_detail: "Detalhes",
		points: "Pontos",
		graphics: "Gráficos",
		partial: "Parciais",
		back: "Voltar",
		configuration: "Configuração",
		portuguese: "Português",
		english: "Inglês",
      exercises_number: "Num. exercícios"
	});
	$translateProvider.preferredLanguage("pt_BR");	
	//$translateProvider.fallbackLanguage("en_US");
	//$translateProvider.use('pt_BR');
	//$translateProvider.rememberLanguage(true);
  // if none of the above states are matched, use this as the fallback
  //$urlRouterProvider.otherwise('/app/resume');
});

